package com.wei.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.client.UcenterClientFeign;
import com.wei.entity.Comment;
import com.wei.service.CommentService;
import com.wei.service_base.exception.XueYuanException;
import com.wei.service_base.vo.BaseMemberVo;
import com.wei.utils.JwtUtils;
import com.wei.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wjx
 * @ClassName CommentController
 * @description: TODO
 * @date 2022-11-29 21:15
 * @version: 1.0
 */
@RestController
@RequestMapping("/eduservice/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UcenterClientFeign ucenterClientFeign;

    /**
     * 分页查询
     *
     * @param current
     * @param limit
     * @return
     */
    @GetMapping("/getCommentPage/{courseId}/{current}/{limit}")
    public R getCommentPage(@PathVariable String courseId,
                            @PathVariable Long current,
                            @PathVariable Long limit) {


        Page<Comment> page = new Page<>(current, limit);

        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getCourseId, courseId).orderByDesc(Comment::getGmtCreate);

        commentService.page(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();

        map.put("records", page.getRecords());
        map.put("current", page.getCurrent());
        map.put("size", page.getSize());
        map.put("total", page.getTotal());
        map.put("pages", page.getPages());
        map.put("hasNext", page.hasNext());
        map.put("hasPrevious", page.hasPrevious());

        return R.ok().data("map", map);
    }

    @PostMapping("/addComment")
    public R addComment(@RequestBody(required = false) Comment comment, HttpServletRequest request) {

        String id = JwtUtils.getMemberIdByJwtToken(request);

        System.out.println(id);

        if (StrUtil.isEmpty(id)) {
            throw new XueYuanException(20001, "请先登录");
        }

        //用户id不为空，则根据id查出用户基本信息 -- 远程调用
        BaseMemberVo memberVo = ucenterClientFeign.getUserInfoById(id);

        comment.setMemberId(id);
        comment.setAvatar(memberVo.getAvatar());
        comment.setNickname(memberVo.getNickname());

        commentService.save(comment);

        return R.ok();
    }
}
